package com.ks.service;

import com.ks.base.BaseService;
import com.ks.dao.*;
import com.ks.entity.*;
import com.ks.util.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service("practiceService")
public class PracticeService<T> extends BaseService<T> {
    private final static Logger log = Logger.getLogger(PracticeService.class);

    @Autowired
    private PracticeDao<T> dao;
    @Autowired
    private DepositoryDao<T> depositoryDao;
    @Autowired
    private QuestionDao<T> questionDao;
    @Autowired
    private ContentDao<T> contentDao;
    @Autowired
    private PaperStudentDao<T> paperStudentDao;
    @Autowired
    private PaperStudentQuestionDao<T> paperStudentQuestionDao;
    @Autowired
    private StudentQuestionDao<T> studentQuestionDao;
    @Autowired
    private ContentQuestionDao<T> contentQuestionDao;
    public PracticeDao<T> getDao() {
        return dao;
    }

    /**
     *
     * list 取的是content表中所有知识点
     * Map 中 count 是当前题库中的所有题目数量
     * @param user
     * @return
     */
    public List<Content> practiceIndex(User user) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        List<T> listQuestion = questionDao.queryList(null);
        map.put("user_id",user.getId());
        int countPractice = dao.queryByCount(map);
        List<T> list = depositoryDao.queryList(null);
        List<Content> listContent = null;
        if (list.size()>0) {
            Depository entity = (Depository) list.get(0);
            resultMap.put("depoName",entity);
            map.put("despid",entity.getId());
           listContent = (List<Content>) contentDao.queryList(map);

        }
        return listContent;
    }
    @Transactional
    public Map<String, Object> createAnalogPaper(User user, String[] str) {
        Map<String, Object> resultMap = new HashMap<>();
        PaperStudent entity = new PaperStudent();
        ApplicationContext ac = null;
        PaperStudentQuestion paperStudentQuestion = null;
        entity.setUser_id(user.getId());
        paperStudentDao.add(entity);
        resultMap.put("paperid",entity.getId());
        //系统会从题库随机抽取20道单选题、
        // 10道多选题和20道判断题，难题占比均为20%，
        // 即单选中有4道难题，多选中有2道难题，
        // 判断题中有4道难题
        int countsingle = 20;
        int countjudge = 20;
        int countmuti = 10;
        List<Map<String, Object>> listQuestion = new ArrayList<>();
        Map<String, Object> mapQuestion1 = new HashMap<>();
        mapQuestion1.put("questiontype_id", 1);
        mapQuestion1.put("count", 10);
        mapQuestion1.put("rate", 20);
        mapQuestion1.put("easyrate", 20);
        listQuestion.add(mapQuestion1);
        Map<String, Object> mapQuestion2 = new HashMap<>();
        mapQuestion2.put("questiontype_id", 2);
        mapQuestion2.put("count", 10);
        mapQuestion2.put("rate", 20);
        mapQuestion2.put("easyrate", 20);
        listQuestion.add(mapQuestion2);
        Map<String, Object> mapQuestion3 = new HashMap<>();
        mapQuestion3.put("questiontype_id", 3);
        mapQuestion3.put("count", 10);
        mapQuestion3.put("rate", 20);
        mapQuestion3.put("easyrate", 20);
        listQuestion.add(mapQuestion3);
        //难题数量
        for (Map<String, Object> question : listQuestion) {
            Map<String, Object> map = new HashMap<>();
            map.put("str", str);
            map.put("questiontype_id", question.get("questiontype_id"));
            map.put("type", 1); //难题
            List<ContentQuestion> qdlist = contentQuestionDao.queryListByContentids(map);
            int diffCount = (int) question.get("count")*(int) question.get("rate")/100;
            if (diffCount < qdlist.size()) {
                //t_ks_paper_question表添加记录 难题
                int[] setdiff = RandomUtils.getDifferentRandom(diffCount, qdlist.size());
                for (Integer i : setdiff) {
                    ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
                    paperStudentQuestion = (PaperStudentQuestion) ac.getBean("paperStudentQuestion");
                    paperStudentQuestion.setPaper_user_id(entity.getId());
                    ContentQuestion contentQuestion = (ContentQuestion) qdlist.get(i);
                    paperStudentQuestion.setQuestion_id(contentQuestion.getQuestion_id());
                    paperStudentQuestionDao.add(paperStudentQuestion);
                }
            } else {
                resultMap.put("msg","难题数量不够");
            }
                map.put("type", 2); //易题
                List<ContentQuestion> qslist = contentQuestionDao.queryListByContentids(map);
                //简单题数量
                int easyCount = (int) question.get("count")*(int) question.get("easyrate")/100;
                if (easyCount < qslist.size()) {
                    //t_ks_paper_question表添加记录 简单题
                    int[] seteasy = RandomUtils.getDifferentRandom(easyCount, qslist.size());
                    for (Integer i : seteasy) {
                        ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
                        paperStudentQuestion = (PaperStudentQuestion) ac.getBean("paperStudentQuestion");
                        paperStudentQuestion.setPaper_user_id(entity.getId());
                        ContentQuestion contentQuestion = (ContentQuestion) qslist.get(i);
                        paperStudentQuestion.setQuestion_id(contentQuestion.getQuestion_id());
                        paperStudentQuestionDao.add(paperStudentQuestion);
                    }
                } else {
                    resultMap.put("msg","简单题数量不够");
                }
                map.put("type", 3); //中间题
                List<ContentQuestion> qmlist = contentQuestionDao.queryListByContentids(map);
                //中间难度题数量
                int midCount = (int) question.get("count") - easyCount - diffCount;
                if (midCount < qmlist.size()) {
                    //t_ks_paper_question表添加记录 简单题
                    int[] seteasy = RandomUtils.getDifferentRandom(midCount, qmlist.size());
                    for (Integer i : seteasy) {
                        ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
                        paperStudentQuestion = (PaperStudentQuestion) ac.getBean("paperStudentQuestion");
                        paperStudentQuestion.setPaper_user_id(entity.getId());
                        ContentQuestion contentQuestion = (ContentQuestion) qmlist.get(i);
                        paperStudentQuestion.setQuestion_id(contentQuestion.getQuestion_id());
                        paperStudentQuestionDao.add(paperStudentQuestion);
                    }
                } else {
                    resultMap.put("msg","中间题数量不够");
                }
            }
        return resultMap;
    }

    /**
     *
     * @param paperid 练习考试id
     * @return
     */
    public Map<String,Object> queryPaperByPaperId(String paperid) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> questionMap = new HashMap<>();
        questionMap.put("paper_user_id", paperid);
        questionMap.put("questiontype_id", 1);
        //每道题的分值

        List<Map<String, String>> singlelist = paperStudentQuestionDao.queryQuestionDetails(questionMap);
        resultMap.put("singlelist", singlelist);
        resultMap.put("singlecount", singlelist.size());
        resultMap.put("singlescore", 3);
        questionMap.put("questiontype_id", 2);
        //每道题的分值
        List<Map<String, String>> mutilist = paperStudentQuestionDao.queryQuestionDetails(questionMap);
        resultMap.put("mutilist", mutilist);
        resultMap.put("muticount", mutilist.size());
        resultMap.put("mutiscore", 5);

        questionMap.put("questiontype_id", 3);
        List<Map<String, String>> judgelist = paperStudentQuestionDao.queryQuestionDetails(questionMap);
        resultMap.put("judgelist", judgelist);
        resultMap.put("judgecount", judgelist.size());
        resultMap.put("judgescore", 2);
        resultMap.put("paperid", paperid);
        resultMap.put("questions", singlelist.size()+mutilist.size()+judgelist.size());

        return resultMap;
    }

    @Transactional
    public Map<String, Object> calculation(String paperid) {
        // TODO Auto-generated method stub
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> questionMap = new HashMap<>();
        Map<String, Object> singlemap = new HashMap<>();
        Map<String, Object> judgemap = new HashMap<>();
        Map<String, Object> mutimap = new HashMap<>();
        int singlecorr = 0;
        int muticorr = 0;
        int judgecorr = 0;
        questionMap.put("paper_user_id",paperid);
        List<Map<String, String>> list = paperStudentQuestionDao.queryQuestionDetails(questionMap);
        ApplicationContext ac = null;
        StudentQuestion studentQuestion = null;
        for (Map<String, String> map : list) {
            //多项选择题
            // 问题选项
            Question qc = (Question) questionDao.queryById(map.get("question_id"));
            if ("1".equals(String.valueOf(map.get("questiontype_id")))) {
                if (qc.getAnswer().equals(map.get("answer"))) {
                    singlecorr = singlecorr + 1;
                } else {
                    ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
                    studentQuestion = (StudentQuestion) ac.getBean("studentQuestion");
                    studentQuestion.setQuestion_id(qc.getId());
                    studentQuestionDao.add(studentQuestion);
                }
            } else if ("2".equals(String.valueOf(map.get("questiontype_id")))) {
                if (qc.getAnswer().equals(map.get("answer"))) {
                    muticorr = muticorr + 1;
                }else {
                    ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
                    studentQuestion = (StudentQuestion) ac.getBean("studentQuestion");
                    studentQuestion.setQuestion_id(qc.getId());
                    studentQuestionDao.add(studentQuestion);
                }
            } else {
                if (qc.getAnswer().equals(map.get("answer"))) {
                    judgecorr = judgecorr + 1;
                } else {
                    ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
                    studentQuestion = (StudentQuestion) ac.getBean("studentQuestion");
                    studentQuestion.setQuestion_id(qc.getId());
                    studentQuestionDao.add(studentQuestion);
                }
            }
        }
        Map<String, Object> typeMap = new HashMap<>();
        typeMap.put("paper_id", paperid);
        typeMap.put("questiontype_id", 1);
        int singlescore = getMap(singlemap, singlecorr, typeMap,3,10);
        typeMap.put("questiontype_id", 3);
        int judgescore = getMap(judgemap, judgecorr, typeMap,2,10);
        typeMap.put("questiontype_id", 2);
        int mutiscore = getMap(mutimap, muticorr, typeMap,5,10);
        resultMap.put("single", singlemap);
        resultMap.put("judge", judgemap);
        resultMap.put("muti", mutimap);
        int singlegoals = singlecorr * singlescore;
        int judgecorrgoals = judgecorr * judgescore;
        int mutigoals = muticorr * mutiscore;
        int total = singlegoals + judgecorrgoals + mutigoals;
        resultMap.put("score", total);
        ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
        PaperStudent paperStudent= (PaperStudent) ac.getBean("paperStudent");
        paperStudent.setId(Integer.parseInt(paperid));
        paperStudent.setScore(total);
        paperStudent.setSingle(singlecorr*3);
        paperStudent.setMuti(muticorr*5);
        paperStudent.setJudge(judgecorr*2);
        paperStudent.setUpdatetime(new Date());
        paperStudentDao.updateBySelective(paperStudent);
        return resultMap;
    }
    private int getMap(Map<String, Object> map, int corr, Map<String, Object> typeMap,int score,int count) {
        map.put("score", score);
        map.put("count", count);
        map.put("corrCount", corr);
        return score;
    }
    private boolean compare(String s, String t) {
        byte[] b1 = s.getBytes();
        byte[] b2 = t.getBytes();
        int[] bCount = new int[256];
        for(int i=0;i<256;i++){
            bCount[i] = 0;
        }
        for(int i=0;i<b1.length;i++)
            bCount[b1[i]-'0']++;
        for(int i=0;i<b2.length;i++)
            bCount[b2[i]-'0']--;
        for(int i=0;i<256;i++){
            if(bCount[i]!=0)
                return false;
        }
        return true;
    }

    public Map<String, Object> queryUserPaperResults(String paperid, PaperStudent entity) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        map.put("paper_user_id",paperid);
        map.put("questiontype_id",1);
        List<Map<String, Object>> singlelist = paperStudentQuestionDao.queryQuestionDetailAnswers(map);
        map.put("questiontype_id",2);
        List<Map<String, Object>> mutilist = paperStudentQuestionDao.queryQuestionDetailAnswers(map);
        map.put("questiontype_id",3);
        List<Map<String, Object>> judgelist =   paperStudentQuestionDao.queryQuestionDetailAnswers(map);
        resultMap.put("singlelist", singlelist);
        resultMap.put("singlecount",singlelist.size());
        resultMap.put("sincorr",entity.getSingle()/3);

        resultMap.put("mutilist", mutilist);
        resultMap.put("muticount",mutilist.size());
        resultMap.put("muticorr",entity.getSingle()/5);

        resultMap.put("judgelist", judgelist);
        resultMap.put("judgecount",judgelist.size());
        resultMap.put("judgecorr",entity.getSingle()/2);
        return resultMap;

    }
    public Map<String, Object> paperWarnning(String paperid) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        map.put("paper_user_id",paperid);
        List<Map<String, Object>> list = paperStudentQuestionDao.queryQuestionDetailAnswers(map);
        int count = 0;
        for (Map<String, Object> stringObjectMap : list) {
            if (null==stringObjectMap.get("answer")) {
                count = count + 1;
            }
        }
        resultMap.put("count",count);
        return resultMap;

    }
}
